package ch10_IO流与文件.数据流;

import java.io.*;

/**
 * @author 挚爱之夕
 * @date 2021/8/27 - 08 - 27 - 16:31
 * @Description: ch10.数据流
 * @Version: 1.0
 */
public class DataStreamDemo {
    String dataFile= "D:/cpu.dat";  //用于写出和读入的字节文件
    //要写出的数据
    long[] ids = {100001,100002,100003};
    String[] names = {"酷睿 i9-9900k ","锐龙 R7-2700X","志强 E5-2620v4"};
    float[] price = {4599,2599,3699};
    int[] counts = {16,20,10};
    public static void main(String[] args) {
        DataStreamDemo demo = new DataStreamDemo();
        demo.save();
        demo.load();
    }

    private void save() {
        try(FileOutputStream fos = new FileOutputStream(dataFile);
            DataOutputStream dos = new DataOutputStream(fos)){
            for (int i = 0; i < ids.length; i++) {
                dos.writeLong(ids[i]);//写出long型数据
                dos.writeUTF(names[i]);//以UTF编码写出字符串
                dos.writeFloat(price[i]);//写出float型数据
                dos.writeInt(counts[i]);//写出int型数据
            }
        }catch (IOException e){
            System.out.println("写出发生了 I/O错误！");
            System.exit(-1);//退出程序
        }
    }

    private void load() {
        System.out.printf("%-10s%-13s%8s%13s\n","id","name","price","inventory");
        for (int i = 0; i < 44; i++) {
            System.out.print("-");//打印分割符
        }
        System.out.println();
        try(FileInputStream fis = new FileInputStream(dataFile);
            DataInputStream dis = new DataInputStream(fis)){
            while(true){//一直读到直至循环体抛出IOException异常
                long id = dis.readLong();
                String name = dis.readUTF();
                float price = dis.readFloat();
                int inventory = dis.readInt();
                System.out.printf("%-10d%-12s%8.1f%12d\n",id,name,price,inventory);
            }

        }catch (IOException e){
            System.exit(-1);
        }
    }
}
